#!/usr/bin/env python

"""
Used to work around the issue of symlinks in the offline HTML docs on
Windows.

Because Windows browsers do not know how to interpret Cygwin symlinks, we
instead need to fix up relative URIs in the HTML to avoid the use of
symlinked paths.
"""

import argparse
import os
import re
import sys


def fixup_doc_link(link_path, verbose=False):
    dirname = os.path.dirname(link_path)
    link_real_path = os.path.realpath(link_path)

    for curdir, dirs, files in os.walk(dirname):
        # The path of the link relative to the current file; this is the
        # path that is currently used in URLs
        old = os.path.relpath(link_path, curdir)

        # The new relative path after resolving the link
        new = os.path.relpath(link_real_path, curdir)
        regexp = re.compile(r'(src|href)="' + re.escape(old))
        repl = r'\1="' + new
            
        for filename in files:
            if not filename.endswith('.html'):
                continue

            if verbose:
                print('    -> ' + filename)

            filepath = os.path.join(curdir, filename)
            with open(filepath) as fobj:
                text = fobj.readlines()

            with open(filepath, 'w') as fobj:
                for line in text:
                    line = regexp.sub(repl, line)
                    fobj.write(line)


def main(argv=None):
    doc = [l.rstrip() for l in __doc__.strip().splitlines()] + ['']
    split = doc.index('')
    usage = '\n'.join(doc[:split])
    epilog = '\n'.join(doc[split:]).strip()
    parser = argparse.ArgumentParser(usage=usage, epilog=epilog)
    parser.add_argument('dir', metavar='DIR',
            help='path to the Sage HTML documentation')
    parser.add_argument('-V', '--verbose', action='store_true',
            help='verbose output')
    args = parser.parse_args()

    for curdir, dirs, files in os.walk(args.dir):
        # For the purposes of this script we are only interested in symlinks to
        # directories which, slightly paradoxically, show up in the dirs list
        # in os.walk...
        for dirname in dirs:
            dirpath = os.path.join(curdir, dirname)
            if os.path.islink(dirpath):
                if args.verbose:
                    print("Fixing up links to {}".format(dirpath))
                fixup_doc_link(dirpath, verbose=args.verbose)


if __name__ == '__main__':
    sys.exit(main())
